import os
import time
import sys

######### below: universal modules #########################
def mode():
	print "Select mode:\n1 - based on time\n2 - based on application\
	\n3 - based on process id\n\nAdditional options:\n4 - Help"
	selection = raw_input('Your choice (1,2,3 and 4 allowed): ')

	while True: 
		try: 
 			int(selection)
			while int(selection) not in range(1, 5): 
            			selection = raw_input('\nInvalid number!Valid range is 1-4:')

			break
    
		except ValueError: 
		        selection = raw_input('\nYou must specify a number!Valid range is 1-4:')
	return selection

def environment():
	"""Zistenie prostredia pre ucely definovania vypinacieho prikazu"""
	ifroot = int(getCommandOutput( "whoami | grep root | wc -l" ))
#	return ifroot
	ifkde = int(getCommandOutput( "ps ax | grep kdm | wc -l" ))
	ifgnome = int(getCommandOutput( "ps ax | grep gdm | wc -l" ))
	if ifroot > 0:
		envir = "root"
	elif ifkde > 0:
		envir = "kde"
	elif ifgnome > 0:
		envir = "gnome"
	else:
		envir = "none"
	return envir

def getCommandOutput(command): 
 	    childin,childout,childerr = os.popen3(command) 
 	    data = childout.read().strip() #toto je otazne ci tam ta nula je potrebna [0].strip()
 	    err = childerr.read() 
 	    errcode = childout.close() 
 	    if err: 
 	        error = '%s->%s' % (command, err) 
 	        raise RuntimeError, error 
 	    return data 


def sdcommand(env):
	if env == "root":
		sdcommand = "shutdown -h now"
		print "You are logged on as root, that's good"
	elif env == "kde":
		sdcommand = "kdmctl shutdown halt trynow"
		print "Seems you are running KDE with kdm"
	elif env == "gnome":
		sdcommand = "kdmctl shutdown halt trynow"
		print "Seems you are running GNOME with gdm"
	else:
		sdcommand = "none"
		print "I'm sorry, it seems I cant shut down the PC\n \
		please log in as root"
	return sdcommand

def sdmodule(command):
	output = os.WEXITSTATUS(os.system(command))
	if output > 0:
		print "Shutdown failed. I'm sorry. Try run this script as root."

def help():
	print "\nAUTOSHUTDOWN HELP:\nAutoshutdown is python CLI script to shutdown your PC\n\
-after some period of time\n-when some application terminates\n\
-when some process terminates\n\
	\n\n\
Currently detection of if some application is running is quite primitive based on pgrep and entered string. For reliable results use detection \
based on process ID."
	print "\nFuture plans: adding CPU utilization detection"
############### above: universal modules ############
############### below: meta-modules#####

def metatime():
	minutes = int(cakanie())
	countdown(minutes)

def metaapp():
	app = app1()
	ifruns(app)
	stillrunning(app)

def metapid():
	pid = findpid()
	ifpruns(pid)
	stillrunningp(pid)

############### above: meta-modules#####
############### below: application based modules#####
def app1():
	app0 = raw_input ("Which application?  ")
#	print app0
	return app0

def running(app):
	running = int(getCommandOutput("pgrep %s | wc -l" % app))
	return running


def stillrunning(app):
	stillrunning = "yes"
	sys.stdout.write("Application/process running")
	sys.stdout.flush()
	while stillrunning == "yes" :
		runningB = running(app)
		if runningB == 0:
			print ""
			print "No such application/process is running any longer"
			stillrunning = "no"
			break
		else :
			sys.stdout.write(".")
			sys.stdout.flush()
			time.sleep(1)
	return stillrunning

def ifruns(app):
	running = int(getCommandOutput("pgrep %s | wc -l" % app))
	if running == 0:
		print "Sorry, no such application running, rerun the script"
		sys.exit()
	return app
	
############### above: application based modules ############
################ below: process ID based modules #############
def stillrunningp(pid):
	stillrunning = "yes"
	sys.stdout.write("Application/process running")
	sys.stdout.flush()
	while stillrunning == "yes" :
		runningB = runningp(pid)
		if runningB == 0:
			print ""
			print "The process is no longer running"
			stillrunning = "no"
			break
		else :
			sys.stdout.write(".")
			sys.stdout.flush()
			time.sleep(1)
	return stillrunning

def findpid():
	pid = raw_input ("Number of process:  ")
#	print pid
	return pid

def ifpruns(pid):
	running = int(getCommandOutput("ps ax | grep %s | grep -v grep | wc -l" % pid))
	print running
	if running == 0:
		print "Sorry, no such process running, rerun the script"
		sys.exit()
	return pid

def runningp(pid):
	running = int(getCommandOutput("ps ax | grep %s | grep -v grep | wc -l" % pid))
	return running

################ above: process ID based modules #############
############### below: time based modules################


def cakanie():
	waiting = raw_input('Minutes to wait, range 1-10000:')

	while True: 
		try: 
 			int(waiting)
			while int(waiting) not in range(1, 10000): 
            			waiting = raw_input('\nInvalid number!Valid range is 1-10000:')

			break
    
		except ValueError: 
		        waiting = raw_input('\nYou must specify a number!Valid range is 1-10000:')
	return waiting

def countdown1(minutes): #stary countdown neplanujem pouzit
 	""" countdown minutes im minute intervals"""
	expired = "no"
	while expired == "no":
		print "Remaining minutes:", minutes
		minutes = minutes - 1
		if minutes <= 0:
			print "Minutes expired"
			expired = "yes"
		time.sleep(1) #this need to be changed to 60

def countdown(minutes):
 	""" countdown minutes im minute intervals"""
	expired = "no"
	while expired == "no":
		sys.stdout.write("Remaining time (min): ")
		sys.stdout.write("%s%s\r" % (minutes," "))
		sys.stdout.flush()
		minutes = minutes - 1
		if minutes <= 0:
			print "!!!!!!! Waiting is over !!!!!!"
			expired = "yes"
		time.sleep(1) #this need to be changed to 60

############### above: time based modules################
# ######## end of definitions #######################

env = environment()
sdcommand = sdcommand(env)
print "Shutdown command will be:",sdcommand
print ""

modeB = int(mode())
print ""

if modeB == 1 :
	metatime()
elif modeB == 2 :
	metaapp()
elif modeB == 3 :
	metapid()
elif modeB == 4 :
	help()
	sys.exit()
	
#sdmodule(sdcommand) #pre testovacie ucely je to vypnute...

############# not used #################
sys.exit ()
print " "
app2 = app1() # zistenie retazca

running = int(getCommandOutput("pgrep %s | wc -l" % app2)) # zistenie kolko prislusnych procesov bezi musi byt pgrep?
print " "
#print running

if running == 0:
	print "Ziadna applikacia zodpovedajuca retazcu " + app2 + " nebezi"
	import sys
	sys.exit ()
else :
	print running , "applikacii zodpoveda retazcu"

waiting2 = int(cakanie ())
print waiting2

envir2 = environment ()
print envir2

countdown(waiting2)	

print (sdcommand(envir2))
